<template>
  <div :class="{'show': show}" class="header-search">
    <el-icon class="search-icon" @click.stop="onShowClick"><Search /></el-icon>
    <el-select
      ref="headerSearchSelectRef"
      v-model="search"
      :remote-method="querySearch"
      filterable
      default-first-option
      remote
      placeholder="搜索页面"
      class="header-search-select"
      @change="change"
    >
      <el-option v-for="item in options" :key="item.path" :value="item" :label="item.title.join(' > ')" />
    </el-select>
  </div>
</template>

<script setup>
import { ref, watch, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import Fuse from 'fuse.js'
import { usePermissionStore } from '@/store/permission'

const permissionStore = usePermissionStore()
const router = useRouter()

// 搜索数据相关
const search = ref('')
const options = ref([])
const searchPool = computed(() => {
  const routes = permissionStore.routes
  
  // 过滤路由
  const res = []
  // 递归提取有效路由
  const generateRoutes = (routes, basePath = '/', prefixTitle = []) => {
    for (const router of routes) {
      // 跳过隐藏的路由
      if (router.hidden) {
        continue
      }

      const data = {
        path: !router.alwaysShow ? basePath + router.path : router.path,
        title: [...prefixTitle]
      }

      if (router.meta && router.meta.title) {
        data.title = [...data.title, router.meta.title]
        
        if (!router.alwaysShow) {
          // 只有未被过滤掉的路由才可能成为搜索结果
          res.push(data)
        }
      }

      // 递归处理子路由
      if (router.children) {
        generateRoutes(router.children, data.path + '/', data.title)
      }
    }
  }
  generateRoutes(routes)
  return res
})

// header search相关
const headerSearchSelectRef = ref(null)
const show = ref(false)

// 初始化Fuse搜索实例
const fuse = computed(() => {
  const options = {
    shouldSort: true,
    threshold: 0.4,
    location: 0,
    distance: 100,
    maxPatternLength: 32,
    minMatchCharLength: 1,
    keys: [{
      name: 'title',
      weight: 0.7
    }, {
      name: 'path',
      weight: 0.3
    }]
  }
  
  return new Fuse(searchPool.value, options)
})

// 监听search值变化
watch(show, (value) => {
  if (value) {
    nextTick(() => {
      headerSearchSelectRef.value.focus()
    })
  }
})

// 点击搜索图标时触发
function onShowClick() {
  show.value = !show.value
  if (show.value) {
    headerSearchSelectRef.value && headerSearchSelectRef.value.focus()
  }
}

// 查询搜索结果
function querySearch(query) {
  if (query !== '') {
    options.value = fuse.value.search(query)
  } else {
    options.value = []
  }
}

// 选择搜索结果后触发
function change(val) {
  router.push(val.path)
  search.value = ''
  options.value = []
  show.value = false
}

// 点击其他区域时关闭搜索
function close() {
  headerSearchSelectRef.value.blur()
  options.value = []
  show.value = false
}

// 添加全局事件监听
// 注意：实际项目中可能需要调整此处实现
document.addEventListener('click', close)
</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;
  display: inline-block;
  position: relative;
  
  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }
  
  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;
    
    :deep(.el-input__inner) {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      border-bottom: 1px solid #d9d9d9;
      vertical-align: middle;
    }
  }
  
  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style> 